import React, { useEffect, useState } from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { Spin, message } from 'antd';
import cloudbase from '../../utils/cloudbase';
import styles from './index.module.less';

/**
 * 身份验证守卫组件
 * 用于保护需要登录才能访问的路由
 */
const AuthGuard = ({ children }) => {
  const [loading, setLoading] = useState(true);
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const location = useLocation();

  useEffect(() => {
    const checkAuthStatus = async () => {
      try {
        setLoading(true);
        const user = await cloudbase.getCurrentUser();
        
        if (user) {
          setIsAuthenticated(true);
        } else {
          message.warning('请先登录');
          setIsAuthenticated(false);
        }
      } catch (error) {
        console.error('检查登录状态失败:', error);
        message.error('检查登录状态失败');
        setIsAuthenticated(false);
      } finally {
        setLoading(false);
      }
    };

    checkAuthStatus();
  }, []);

  if (loading) {
    return (
      <div className={styles.loadingContainer}>
        <Spin tip="验证登录状态..." size="large" />
      </div>
    );
  }

  if (!isAuthenticated) {
    // 将用户重定向到登录页面，并记住他们尝试访问的页面
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  // 用户已通过身份验证，渲染子组件
  return children;
};

export default AuthGuard;